#!/usr/bin/env python3
"""
简化的预读机制测试脚本
"""

import os
import sys
import time

# 添加当前目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
if current_dir not in sys.path:
    sys.path.insert(0, current_dir)

def test_readahead_engine():
    """测试预读引擎基本功能"""
    print("🧪 测试预读引擎基本功能...")
    
    try:
        from readahead_engine import ReadAheadEngine, AccessPattern
        
        # 创建预读引擎
        engine = ReadAheadEngine(
            enable_readahead=True,
            window_size=4,
            max_readahead_pages=16
        )
        
        print("✅ 预读引擎创建成功")
        
        # 模拟顺序访问
        print("📈 模拟顺序访问模式...")
        for i in range(10):
            engine.record_access(i, from_cache=False)
            
            # 获取预读请求
            requests = engine.get_readahead_requests(i)
            if requests:
                print(f"  页面 {i}: 生成 {len(requests)} 个预读请求")
                for req in requests:
                    print(f"    预读页面: {req.page_ids}, 优先级: {req.priority}, 模式: {req.pattern.value}")
        
        # 获取统计信息
        stats = engine.get_statistics()
        print(f"\n📊 预读统计:")
        print(f"  当前模式: {stats['current_pattern']}")
        print(f"  模式置信度: {stats['pattern_confidence']:.2f}")
        print(f"  预读请求数: {stats['stats']['requests_generated']}")
        print(f"  预读页面数: {stats['stats']['pages_prefetched']}")
        
        return True
        
    except Exception as e:
        print(f"❌ 预读引擎测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_page_manager_readahead():
    """测试页面管理器的预读功能"""
    print("\n🗃️ 测试页面管理器预读功能...")
    
    try:
        from page_manager import PageManager
        import tempfile
        
        # 创建临时数据库文件
        with tempfile.NamedTemporaryFile(delete=False, suffix='.db') as temp_file:
            temp_db_path = temp_file.name
        
        try:
            # 创建启用预读的页面管理器
            pm = PageManager(temp_db_path, enable_readahead=True)
            
            print("✅ 预读页面管理器创建成功")
            
            # 分配一些页面
            page_ids = []
            for i in range(10):
                page_id = pm.allocate_page()
                page_ids.append(page_id)
                
                # 写入测试数据
                test_data = f"Test data for page {page_id}".ljust(4096, '0')[:4096].encode()
                pm.write_page(page_id, test_data)
            
            print(f"✅ 分配并写入 {len(page_ids)} 个页面")
            
            # 测试顺序读取
            print("📖 测试顺序读取...")
            start_time = time.time()
            
            for page_id in page_ids:
                data = pm.read_page(page_id)
                print(f"  读取页面 {page_id}: {len(data)} 字节")
            
            read_time = time.time() - start_time
            print(f"✅ 顺序读取完成，耗时: {read_time:.3f}秒")
            
            # 获取预读统计
            if hasattr(pm, 'get_readahead_statistics'):
                readahead_stats = pm.get_readahead_statistics()
                if readahead_stats.get('enabled'):
                    print(f"📊 预读统计:")
                    print(f"  当前模式: {readahead_stats.get('current_pattern', 'unknown')}")
                    stats = readahead_stats.get('stats', {})
                    print(f"  预读请求数: {stats.get('requests_generated', 0)}")
                    print(f"  预读页面数: {stats.get('pages_prefetched', 0)}")
            
            # 清理
            pm.close()
            
        finally:
            # 删除临时文件
            if os.path.exists(temp_db_path):
                os.unlink(temp_db_path)
        
        return True
        
    except Exception as e:
        print(f"❌ 页面管理器预读测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


def test_storage_engine_readahead():
    """测试存储引擎的预读功能"""
    print("\n🏗️ 测试存储引擎预读功能...")
    
    try:
        from storage_engine import StorageEngine, CachePolicy
        import tempfile
        
        # 创建临时数据库文件
        with tempfile.NamedTemporaryFile(delete=False, suffix='.db') as temp_file:
            temp_db_path = temp_file.name
        
        try:
            # 创建启用预读的存储引擎
            engine = StorageEngine(
                db_path=temp_db_path,
                cache_size=32,
                cache_policy=CachePolicy.LRU,
                enable_locking=True,
                enable_readahead=True
            )
            
            print("✅ 预读存储引擎创建成功")
            
            # 分配和写入一些页面
            page_ids = []
            for i in range(20):
                page_id = engine.allocate_page()
                page_ids.append(page_id)
                
                # 写入测试数据
                test_data = f"Storage engine test data for page {page_id}".ljust(4096, '0')[:4096].encode()
                engine.write_page(page_id, test_data)
            
            print(f"✅ 分配并写入 {len(page_ids)} 个页面")
            
            # 测试顺序访问
            print("📖 测试顺序访问模式...")
            start_time = time.time()
            
            for page_id in page_ids[:15]:  # 只读前15个页面
                data = engine.read_page(page_id)
                print(f"  读取页面 {page_id}: {len(data)} 字节")
            
            access_time = time.time() - start_time
            print(f"✅ 顺序访问完成，耗时: {access_time:.3f}秒")
            
            # 获取预读统计
            if hasattr(engine, 'get_readahead_statistics'):
                readahead_stats = engine.get_readahead_statistics()
                print(f"📊 存储引擎预读统计:")
                print(f"  预读启用: {readahead_stats.get('readahead_enabled', False)}")
                
                if 'page_manager' in readahead_stats:
                    pm_stats = readahead_stats['page_manager']
                    print(f"  当前访问模式: {pm_stats.get('current_pattern', 'unknown')}")
                    stats = pm_stats.get('stats', {})
                    print(f"  预读请求数: {stats.get('requests_generated', 0)}")
                    print(f"  预读页面数: {stats.get('pages_prefetched', 0)}")
                
                if 'cache_manager' in readahead_stats:
                    cm_stats = readahead_stats['cache_manager']
                    print(f"  缓存利用率: {cm_stats.get('cache_utilization', 0):.2%}")
                    print(f"  缓存命中率: {cm_stats.get('hit_rate', 0):.2%}")
            
            # 清理
            engine.close()
            
        finally:
            # 删除临时文件
            if os.path.exists(temp_db_path):
                os.unlink(temp_db_path)
        
        return True
        
    except Exception as e:
        print(f"❌ 存储引擎预读测试失败: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """主测试函数"""
    print("🚀 开始简化预读机制测试\n" + "="*50)
    
    success_count = 0
    total_tests = 3
    
    # 测试预读引擎
    if test_readahead_engine():
        success_count += 1
    
    # 测试页面管理器预读
    if test_page_manager_readahead():
        success_count += 1
    
    # 测试存储引擎预读
    if test_storage_engine_readahead():
        success_count += 1
    
    # 总结
    print("\n" + "="*50)
    print(f"📋 测试总结: {success_count}/{total_tests} 测试通过")
    
    if success_count == total_tests:
        print("🎉 所有预读机制测试通过！")
        return True
    else:
        print(f"⚠️ {total_tests - success_count} 个测试失败")
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
